/*
 * Copyright 2013 Agustina Martinez-Garcia

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package uk.ljmu.qudexapps.swfspreadsheet.domain;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.binding.validation.ValidationContext;
import org.springframework.web.multipart.MultipartFile;
import uk.ljmu.metadata.utilities.MetadataUtilities;
import uk.ljmu.qudexapps.swfspreadsheet.listeners.CustonServletContext;
import uk.ljmu.qudexapps.swfspreadsheet.utilities.GeneralUtilities;

public class Files implements Serializable {

    /**
     * */
    private static final long serialVersionUID = 6900745290028683216L;

    private List<DdiObject> ddiObjectList;

    transient private MultipartFile file;

    transient private List<MultipartFile> zipFiles;

    transient static private Logger log = Logger.getLogger(Files.class);
    
    /**
     * Path to the temporary directory holding the user uploaded files
     */
    private String tempDirPath = "";

    /**
     * @param zipFile
     *            the zipFile to set
     */
    public void setZipFiles(List<MultipartFile> zipFiles) {
	this.zipFiles = zipFiles;
    }

    /**
     * @return the zipFile
     */
    public List<MultipartFile> getZipFiles() {
	return zipFiles;
    }

    /**
     * @param file
     *            the file to set
     */
    public void setFile(MultipartFile file) {
	this.file = file;
    }

    /**
     * @return the file
     */
    public MultipartFile getFile() {
	return file;
    }

    public void addZipFile(MultipartFile file) {
	if (this.zipFiles == null) {
	    this.zipFiles = new ArrayList<MultipartFile>();
	}
	if (file.getSize() <= uk.ljmu.qudexapps.swfspreadsheet.utilities.Constants.FILE_MAX_MEM_SIZE)
		this.zipFiles.add(file);
	else {
		try {
			file.transferTo(new File(this.tempDirPath + System.getProperty("file.separator") + file.getOriginalFilename()));
			this.zipFiles.add(file);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//this.zipFiles.add(file);
    }

    public void deleteZipFile(int index) {
	try {
	    this.zipFiles.remove(index);
	    this.ddiObjectList.remove(index);
	} catch (IndexOutOfBoundsException ex) {
	}
    }

    /**
     * @param ddiObject
     *            the ddiObject to set
     */
    public void setDdiObjectList(List<DdiObject> ddiObject) {
	this.ddiObjectList = ddiObject;
    }

    /**
     * @return the ddiObject
     */
    public List<DdiObject> getDdiObjectList() {
	return ddiObjectList;
    }
    public void cleanDDiObjects() {
	if (this.getDdiObjectList() != null && this.getDdiObjectList().size() > 0) {
	    this.getDdiObjectList().clear();	    
	}
    }
    public void cleanZipFiles() {
	//for (MultipartFile file : this.zipFiles) {
	 //   try {
	//	if (file.getInputStream() != null)
	//	    file.getInputStream().close();
	//    } catch (IOException e) {
	//    } catch (Exception e) {
	//	log.error("Error", e);
	//    }
	//}
	this.zipFiles.clear();
    }

    public void validateUploadFile(ValidationContext context) {
	MessageContext messages = context.getMessageContext();
	// ZIP present
	if (!this.file.getOriginalFilename().equals("") && file.getSize() > 0) {
	    if (!file.getContentType().equals(
		    MetadataUtilities.MIMETYPES_MAP.get("zip"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("zip2"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("zip3"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("zip4"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("zip5"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("gtar"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("gzip"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("tar"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("xml"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("xml2"))) {
		messages.addMessage(new MessageBuilder().error().source(
			"files.file").code("invalidZipFile").build());
	    }
	} else {
	    messages.addMessage(new MessageBuilder().error().source(
		    "files.file").code("emptyZipFile").build());
	}
    }

    public void validateConfirmSchemas(ValidationContext context) {
	MessageContext messages = context.getMessageContext();
	// ZIP present
	if (!this.file.getOriginalFilename().equals("") && file.getSize() > 0) {
	    if (!file.getContentType().equals(
		    MetadataUtilities.MIMETYPES_MAP.get("xml"))
		    && !file.getContentType().equals(
			    MetadataUtilities.MIMETYPES_MAP.get("xml2"))) {
		messages.addMessage(new MessageBuilder().error().source(
			"files.file").code("invalidDdiInstance").build());
	    }
	} else {
	    messages.addMessage(new MessageBuilder().error().source(
		    "files.file").code("emptyDdiFile").build());
	}
    }
    
    public void init() {
    	/*AMG original init, following two instructions*/
    	this.zipFiles = new ArrayList<MultipartFile>();
    	this.ddiObjectList = new ArrayList<DdiObject>();
    	File sessionTempDir = (File) CustonServletContext
    		.getMyServletContext().getAttribute(
    			"javax.servlet.context.tempdir");
    	File tempDir;
    	try {
    	    tempDir = File.createTempFile("swf", "qudex", sessionTempDir);
    	    if (!(tempDir.delete())) {
    		throw new IOException("Could not delete temp file: "
    			+ tempDir.getAbsolutePath());
    	    }

    	    if (!(tempDir.mkdir())) {
    		throw new IOException("Could not create temp directory: "
    			+ tempDir.getAbsolutePath());
    	    }

    	    this.setTempDirPath(tempDir.getAbsolutePath());
    	    this.zipFiles = new ArrayList<MultipartFile>();
    	} catch (IOException e) {
    	    log.error("Error in init: ", e);
    	}
        }
    /*public void init() {
	this.zipFiles = new ArrayList<MultipartFile>();
	this.ddiObjectList = new ArrayList<DdiObject>();
    }*/

    public String getTempDirPath() {
		return tempDirPath;
	}

	public void setTempDirPath(String tempDirPath) {
		this.tempDirPath = tempDirPath;
	}

	/*public void destroy() {
	for (MultipartFile file : this.zipFiles) {
	    try {
		if (file.getInputStream() != null)
		    file.getInputStream().close();
	    } catch (IOException e) {
	    }
	}
	this.zipFiles.clear();
    }*/
    public void destroy() {
    	this.zipFiles.clear();
    	File tempDir = new File(this.getTempDirPath());
    	if (tempDir.exists()) {
    	    boolean results = GeneralUtilities.deleteDirectory(tempDir);
    	    if (!results) {
    		log.error("Temporary directory not deleted: "
    			+ tempDir.getAbsolutePath());
    	    }
    	}

        }
}